import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/sub/UserInfoPage.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';

import '../../pojo/ImPojo.dart';
import '../../util/ImConstant.dart';
import '../bloc/GroupAddCubit.dart';
import '../bloc/GroupUserListCubit.dart';
import '../bloc/SelectUsersCubit.dart';
import '../view/MovableView.dart';
import '../view/component/UserIconView.dart';
import 'GroupAddPage.dart';

class GroupUserListPage extends StatefulWidget {
  const GroupUserListPage({super.key});

  @override
  State<StatefulWidget> createState() => GroupUserListSate();
}

class GroupUserListSate extends State<GroupUserListPage> {

  late TextEditingController _editingController;

  @override
  void initState() {
    super.initState();
    _editingController = TextEditingController();
  }

  @override
  Widget build(BuildContext context) {
    var groupUserListCubit = context.watch<GroupUserListCubit>();
    var group = groupUserListCubit.state.imGroup;
    return Scaffold(
        appBar: _buildAppBar(context, group),
        backgroundColor: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
        body: SafeArea(
            child: MovableView(
          headMoveMaxHeight: 100,
          trailMoveMaxHeight: 100,
          backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
          widgetBuilder: (BuildContext context) => _buildBody(context, groupUserListCubit),
        )));
  }

  AppBar _buildAppBar(BuildContext context, ImGroup group) {
    return AppBar(
      leading: InkWell(
        child: const Icon(Icons.chevron_left),
        onTap: () {
          Navigator.of(context).pop();
        },
      ),
      title: Text(
        "聊天成员(${group.groupUserList?.length ?? 0})",
        style: const TextStyle(fontSize: ImConstant.IM_DEFAULT_SIZE, fontWeight: FontWeight.w500),
      ),
      toolbarHeight: ImConstant.IM_APP_BAR_HEIGTH,
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      centerTitle: true,
    );
  }

  Widget _buildBody(BuildContext context, GroupUserListCubit groupUserListCubit) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        _buildSearchPane(context),   // 搜索栏
        Padding(
          padding: const EdgeInsets.only(bottom: 10),
          child: ListSeparator(
            indent: 10,
          ),
        ),
        Expanded(child: _buildGroupUsers(context, groupUserListCubit))
      ],
    );
  }

  Widget _buildSearchPane(BuildContext context) {
    var groupUserListCubit = context.watch<GroupUserListCubit>();
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 10, top: 2, bottom: 2),
      margin: const EdgeInsets.only(bottom: 2),
      height: 40,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          const Icon(Icons.search),
          Expanded(
              child: TextField(
                controller: _editingController,
                decoration: const InputDecoration(
                  contentPadding: EdgeInsets.only(top: 1, bottom: 15, left: 5, right: 5),
                  hintText: '搜索',
                  border: InputBorder.none,
                  fillColor: Colors.white,
                  hoverColor: Colors.white,
                  filled: true,
                  hintStyle: TextStyle(color: Colors.black12),
                ),
                onChanged: (text) {
                  groupUserListCubit.add(GroupUserListKeyEvent(text));
                  _delaySearch(groupUserListCubit, text);
                },
              )),
          Visibility(
              replacement: const SizedBox(
                width: 20,
              ),
              visible: groupUserListCubit.state.search != '',
              child: GestureDetector(
                onTap: () {
                  _editingController.text = '';
                  groupUserListCubit.add(GroupUserListKeyEvent(''));
                  _delaySearch(groupUserListCubit, '');
                },
                child: const Icon(Icons.cancel, color: Colors.grey,),
              ))
        ],
      ),
    );
  }

  Widget _buildGroupUsers(BuildContext context, GroupUserListCubit groupUserListCubit) {
    var searchResults = groupUserListCubit.state.searchResults;
    var session = groupUserListCubit.state.imSession;
    return GridView.builder(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 5, childAspectRatio: 1, crossAxisSpacing: 0.0, mainAxisSpacing: 0.0),
      itemCount: (searchResults.length ?? 0) + 1,
      itemBuilder: (BuildContext context, int index) {
        if (index >= (searchResults.length ?? 0)) {
          return _buildAddUserGroup(context, session);
        }
        var groupUser = searchResults.elementAt(index);
        return _buildGroupUserPane(context, groupUser!);
      },
    );
  }

  Widget  _buildGroupUserPane(BuildContext context, ImGroupUser groupUser) {
    return GestureDetector(onTap: () {
      Navigator.of(context).push(MaterialPageRoute(builder: (context){
        return UserInfoPage(user: groupUser.user!);
      }));
    },
    child: Container(
      color: ImConstant.IM_RESERVE_BACKGROUND_COLOR,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: UserIconView(user: groupUser.user!, iconSize: ImConstant.IM_USER_ICON_SIZE - 10,),
          ),
          Text(groupUser!.userName ?? (groupUser.user?.userName ?? groupUser.userId))
        ],
      ),
    ),);
  }

  Widget _buildAddUserGroup(BuildContext context, ImSession session) {
    return InkWell(
      child: const Icon(Icons.add),
      onTap: () async {
        Navigator.of(context).push(MaterialPageRoute(builder: (context){
          return buildGroupCubit(session, const GroupAddPage());
        }));
      },
    );
  }

  _delaySearch(GroupUserListCubit cubit, String search) {
    Future.delayed(const Duration(milliseconds: 500), () {
      if (search == _editingController.text) {
        cubit.add(GroupUserListSearchEvent(search));
      }
    });
  }
}
